(function ($a) {
    'use strict';
    var app = $a.adminApp;
    app.controller('leiloeiroController.Index',
            function ($scope, RestFactory, cocLoading, $location, $timeout, notificationFactory, $localStorage) {
                $scope.leiloeiros = {};
                $scope.required = true;
                var ctr = {
                    api: '/api/leiloeiros',
                    load: function () {
                        cocLoading.trigger();
                        var self = this;
                        RestFactory.get(self.api).success(function (data) {
                            $scope.list = data;
                            $scope.currentPage = self.currentPage(); //current page
                            $scope.entryLimit = 20; //max no of items to display in a page
                            $scope.filteredItems = $scope.list.length; //Initially for no filter 
                            $scope.totalItems = $scope.list.length;
                            $timeout(function () {
                                cocLoading.trigger();
                            }, 10);
                        }).error(function (data) {
                            $timeout(function () {
                                cocLoading.trigger();
                            }, 10);
                        });
                    },
                    delete: function (id) {
                        RestFactory.delete(this.api + '/' + id).success(function (data) {
                            notificationFactory.success(data.message);
                            ctr.load();
                        }).error(function (data) {
                            notificationFactory.error(data.message);
                        });
                    },
                    currentPage: function () {

                        var hasPage = $localStorage.get(this.$controller);
                        if (!hasPage) {
                            $localStorage.set(this.$controller, 1);
                            hasPage = 1;
                        }
                        return hasPage;
                    },
                    $controller: 'page_' + $location.$$absUrl,
                    $currentPage: function (pageNo) {
                        $localStorage.set(this.$controller, pageNo);
                    }
                };

                ctr.load();
                $scope.setPage = function (pageNo) {
                    $scope.currentPage = pageNo;
                    ctr.$currentPage(pageNo);
                };
                $scope.filter = function () {
                    $timeout(function () {
                        $scope.filteredItems = $scope.filtered.length;
                    }, 10);
                };
                $scope.resetSearch = function () {
                    $scope.filteredItems = $scope.list.length;
                    $scope.search = '';
                };

                $scope.orderByFnc = function (item, forceString) {
                    var forceStr = forceString || false;
                    if (isNaN(item[$scope.orderByColumn]) || forceString) {
                        return item[$scope.orderByColumn];
                    }
                    return parseInt(item[$scope.orderByColumn], 10);
                };
                $scope.sort_by = function (predicate) {
                    //$scope.predicate = predicate;
                    $scope.orderByColumn = predicate;
                    $scope.reverse = !$scope.reverse;
                };
                $scope.delete = function (id) {
                    notificationFactory.confirm({
                        message: 'Deseja apagar esse registro ?',
                        callbackConfirm: function () {
                            ctr.delete(id);
                        }
                    });
                };


            });
    /**
     * Edition leiloeiro
     */
    app.controller(
            'leiloeiroController.Settings',
            function ($scope, notificationFactory, $timeout, hashGen,
                    $routeParams, cocGridDataFactory, $location, RestFactory, cocLoading) {

                var $_id = $routeParams.id || 0, $table = 'leiloeiros', cepPattern = /[0-9]{8}/gi;
                $scope.add = false;
                $scope.LastCEP = '00000000';
                $scope.edit = true;
                $scope.leiloeiro = {};
                function toggleAddSettings() {
                    $scope.add = !$scope.add;
                    $scope.edit = !$scope.edit;
                }
                ;
                
                $scope.contasOptions = [];
                $scope.options = [
                {
                    id:'S',
                    label:'SIM'
                },
                {
                    id:'N',
                    label:'NÃO'
                }
                ];
                
                RestFactory.get('/api/contas').success(function(data){
                    $scope.contasOptions = data;
                });
                $scope.leiloeiro = {};
                
                
                shortcut.add(
                        "Ctrl+S",
                        function () {
                            if ($scope.LeiloeiroForm.$valid) {
                                $scope.save();
                            } else {
                                notificationFactory
                                        .error('Verifique os campos obrigatórios, esse formulário não pode ser submetido');
                            }

                        });

                cocGridDataFactory('all_leiloeiros_system').query(function (data) {
                    $scope.leiloeiros_options = data;
                });
                $scope.save = function ($redirect) {
                    cocLoading.trigger();
                    if ($_id > 0) {
                        cocGridDataFactory($table).update({
                            id: $_id
                        }, $scope.leiloeiro, function () {
                            notificationFactory.success();
                            cocLoading.trigger();
                            redirect($redirect);
                        }, function (e) {
                            notificationFactory.error(e.data.message);
                            cocLoading.trigger();
                        });

                    } else {
                        cocGridDataFactory($table).save(
                                $scope.leiloeiro,
                                function () {
                                    notificationFactory.success();
                                    // $scope.leiloeiro = {};
                                    cocLoading.trigger();
                                    $scope.leiloeiro = {};
                                    redirect($redirect);
                                },
                                function (e) {

                                    notificationFactory
                                            .error(e.data.message);
                                    cocLoading.trigger();
                                });
                    }

                };

                function redirect($redirect) {
                    var $redirect = $redirect === 'true' ? true : false;
                    if ($redirect) {
                        $location.path('/leiloeiros');
                    }
                }

                
                cocLoading.trigger();
                toggleAddSettings();
                
                $scope.autoCep = function(){
                    var cep = $scope.leiloeiro.CEP,
                        pattern = /^\d{8}$/gi;
                        //has validate cep
                        if(pattern.test(cep)){
                            cocLoading.trigger();
                            RestFactory.get('/api/logradouro/'+cep).success(function(ceps){
                                
                                angular.forEach(ceps,function(v,k){
                                    //console.log(obj);
                                    $scope.leiloeiro[k]= v;
                                });
                                cocLoading.trigger();
                            });
                            
                        }
                    
                    
                    
                }
                
                $scope.getDataUser = function () {
                    $scope.hideButtonCancel = true;
                    toggleAddSettings();
                    RestFactory.get('/api/leiloeiros/' + $_id).success(function (data) {
                        $scope.leiloeiro = data['0'];
                       
                        cocLoading.trigger();
                    });
                };
                if ($_id > 0) {
                    //$timeout(function() {
                    $scope.getDataUser();
                } else {
                    $timeout(function () {
                        cocLoading.trigger();
                    });
                }
            });
})(cocApp);